﻿using System;
using System.Globalization;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class FormImportedData : Form
    {
        public delegate void ReLoadStudentMarkDelegate();
        public ReLoadStudentMarkDelegate ReLoadStudentMark;

        private readonly Business.Business _business;
        public FormImportedData()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void FormImportedDataLoad(object sender, EventArgs e)
        {
            LoadMajor();
        }

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }

        private void BtnBrowseFileClick(object sender, EventArgs e)
        {
            txtPath.Text = string.Empty;
            dgvStudentMarks.Rows.Clear();

            var openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = openFileDialog.FileName;
                if (!ExcelUtils.ImportExcelOnRange(
                      openFileDialog.FileName, dgvStudentMarks, txtFrom.Text, txtTo.Text, txtColumns.Text, (int)nudSheet.Value))
                    MessageBox.Show(@"File không hợp lệ");
            }

        }

        private void DgvStudentMarksRowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            lblCount.Text = string.Format("Số dòng: {0}", dgvStudentMarks.RowCount);
        }


        private void BtnAddMarkStudentsClick(object sender, EventArgs e)
        {
            try
            {
                bool isUpdate = false;
                if (MessageBox.Show(@"Nếu có sình viên trùng bạn có muốn update không?", "QL Thực tập", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    isUpdate = true;
                }

                // Delete Old data
                var idMajor = ((Major)cboMajors.SelectedItem).Id;
                //var kindMark = cboKindMark.SelectedIndex + 1;
                var kindMark = cboKindMark.SelectedIndex + 1;
                var term = false;

                if (kindMark == 2)
                    term = true;

                //_business.DeleteOldStudent(idMajor, term);

                for (var i = 0; i < dgvStudentMarks.RowCount; i++)
                {
                    // Add Student
                    var name = (dgvStudentMarks.Rows[i].Cells["Fullname"].Value.ToString().Trim() +" "+
                                dgvStudentMarks.Rows[i].Cells["Student"].Value.ToString().Trim());

                    //var birthday = DateTime.ParseExact(dgvStudentMarks.Rows[i].Cells["Birthday"].Value.ToString().Trim(), "ddMMyy", new CultureInfo("fr-FR"));
                    DateTime birthday;
                    if (!DateTime.TryParseExact(dgvStudentMarks.Rows[i].Cells["Birthday"].Value.ToString().Trim(), "ddMMyy", new CultureInfo("en-GB"), DateTimeStyles.None, out birthday))
                    {
                        birthday = DateTime.Now;
                    }

                    if (birthday < new DateTime(1756,2,1) || birthday > new DateTime(9999,12,1))
                    {
                        birthday = DateTime.Now;
                    }

                    var student = new Student
                                      {
                                          Code = dgvStudentMarks.Rows[i].Cells["Code"].Value.ToString().Trim(),
                                          Name = name,
                                          IdMajor = idMajor,
                                          DateOfBirth = birthday,
                                          Term = term,
                                      };

                    // Add StudentMark
                    var studentmark = new StudentMark
                                          {
                                              IdKindMark = kindMark,
                                              Mark = Convert.ToDouble(dgvStudentMarks.Rows[i].Cells["Average"].Value),
                                              IsDebt = false
                                          };

                    _business.AddOrEditStudentAndMark(student, studentmark, isUpdate);

                }

                if (ReLoadStudentMark != null)
                {
                    ReLoadStudentMark();
                }

                MessageBox.Show("Done!");

                Dispose();
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
                MessageBox.Show(ex.Message);
            }
        }
    }
}
